package com.ztw.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.ztw.yygh.common.Helper.JwtHelper;
import com.ztw.yygh.common.exception.YyghException;
import com.ztw.yygh.common.result.Result;
import com.ztw.yygh.common.result.ResultCodeEnum;
import com.ztw.yygh.model.user.UserInfo;
import com.ztw.yygh.user.service.UserInfoService;
import com.ztw.yygh.user.utils.ConstantPropertiesUtil;
import com.ztw.yygh.user.utils.HttpClientUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//微信操作接口
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeiXinApiController {

    @Resource
    private UserInfoService userInfoService;
    /**
     * 获取微信登录参数    生成微信扫描二维码
     */
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result genQrConnect() {
        Map<String, Object> map = new HashMap<>();
        try {
            String wxOpenRedirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            map.put("redirect_uri", wxOpenRedirectUrl);
            map.put("state", System.currentTimeMillis() + "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return Result.ok(map);
    }

    //微信扫码的回调方法，得到扫描人的信息
    @GetMapping("callback")
    public String callback(String code, String state) {
        //1.获取临时票据
        System.out.println("Code:" + code);
        if (StringUtils.isEmpty(state) || StringUtils.isEmpty(code)) {
            System.out.println("非法回调请求");
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        try {
            //2.使用httpclient请求这个地址,获取数据
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println(accessTokenInfo);
            //从字符串获取数据
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String accessToken = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            //判断数据库中是否存在该用户--openid
            UserInfo userInfo=userInfoService.selectWxInfoOpenId(openid);
            if(userInfo==null){//数据库不存在该用户

                //3.拿着openid 和 access_token 请求微信地址，得到扫描人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("result:"+resultUserInfo);
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);
                //解析用户信息
                String nickname = resultUserInfoJson.getString("nickname");
                String headimgurl = resultUserInfoJson.getString("headimgurl");
                //添加扫码人信息
                userInfo = new UserInfo();
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);


            //判断是否有手机号，手机号为空则返回openid
            //手机号不为空则返回空openid
            //用来判断是否绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
